package com.itcast.springboot.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class QiNiuYunUtil {
	// 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "KMqByuSAEyMESKd8kxQrFphlTO9_WdqwuTK36aLP";
    private static final String SECRET_KEY = "DP9idBqfCukQfo6v8_EanoNBq0p5CxefvbWLlLJj";

    // 要上传的空间
    private static final String bucketname = "waste-recovery";

    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    private static final String DOMAIN = "cen.roadvast.top";

    public static final String style = "imageMogr2/auto-orient/thumbnail/1154x/blur/1x0/quality/75|watermark/2/text/aHR0cDovL3d3dy5nb25nc3VuZnVzdS50b3A=/font/5a6L5L2T/fontsize/720/fill/IzAwMDAwMA==/dissolve/80/gravity/SouthEast/dx/10/dy/10";

    //七牛云上的图片的固定前缀
    private static String serverUrl = "http://" + DOMAIN + "/";

    public String getUpToken() {
        return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
    }

    //base64方式上传
    public String put64image(byte[] base64, String key) throws Exception{
        String file64 = Base64.encodeToString(base64, 0);
        Integer l = base64.length;
        String url = "http://upload-z2.qiniu.com/putb64/" + l + "/key/"+ UrlSafeBase64.encodeToString(key);
        //非华东空间需要根据注意事项 1 修改上传域名
        //upload.qiniu.com 上传域名适用于华东空间。华北空间使用 upload-z1.qiniu.com，华南空间使用 upload-z2.qiniu.com，北美空间使用 upload-na0.qiniu.com。
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        if (response.code() == 200){
            System.out.println(serverUrl + key);
            return serverUrl + key;
        }
        return "-1";
    }

    // 删除图片
    public Integer deleteImg(String key) {
        if (key != null && !key.trim().equals("") && !key.equals(serverUrl)){
            log.info("user_url not exist...");
            return -1;
        }
        // 实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(auth);
        // 截取图片路径：图片名 + 图片后缀
        key = key.replace(serverUrl, "");
        System.out.println(key);
        try {
            // 调用delete方法移动文件
            bucketManager.delete(bucketname, key);
        } catch (QiniuException e) {
            // 捕获异常信息
            Response r = e.response;
            System.out.println(r.toString());
            return -1;
        }
        return 1;
    }
}
